package com.sogoodsoft.unit.basic;

import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author lxz
 * 
 *        <li>Hibernate junit test base class</li> <li>测试初始化时自动加载hibernate配置文件</li>
 *        <li>继承DAOTestBase类后，可编写相应方法测试hibernate功能</li> <li>
 *         此方法不加载spring配置，比spring测试快</li>
 */
public class DAOTestBase {

	protected static SessionFactory sessionFactory;
	protected static Session session;
	protected Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 加载hibernate配置文件
	 */
	@BeforeClass
	public static void loadConfig() {
		// sessionFactory = new
		// Configuration().configure("hibernate.cfg.xml").buildSessionFactory();

		System.out.println("load config");
		try {
			sessionFactory = new AnnotationConfiguration().configure(
					"hibernate.cfg.xml").buildSessionFactory();
			session = sessionFactory.openSession();
			session.beginTransaction();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * 加上@Test后就成为一个测试了
	 */

	@SuppressWarnings("unchecked")
    public void queryDemo() {
		System.out.println("query test");
		try {
			Session session = sessionFactory.openSession();
			Query query = session.getNamedQuery("user.query");
			List<Map<?, ?>> list = query.list();
			System.out.println(list.size());
			for (Map<?, ?> map : list) {
				System.out.println(map.get("email"));
			}
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void save(Object obj) {
		print("保存实体");
		session.save(obj);
	}

	/**
	 * 查询方法，仅支持String,Long型参数，其它参数请写进HQL里
	 * 
	 * @param hql
	 * @param arg
	 * @return
	 */
	@SuppressWarnings("unchecked")
    public <T> List<T> find(String hql, Object... arg) {
		print("查询实体");
		List<T> list = null;
		Query query = session.createQuery(hql);
		for (int i = 0; i < arg.length; i++) {
			Object obj = arg[i];
			print(obj.getClass().getName());
			if (obj.getClass().getName().equalsIgnoreCase(
					String.class.getName())) {
				query.setString(i, (String) obj);
			} else if (obj.getClass().getName().equalsIgnoreCase(
					Long.class.getName())
					|| obj.getClass().getName().equalsIgnoreCase(
							Integer.class.getName())) {
				query.setLong(i, new Long(String.valueOf(obj)));
			}
		}
		list = query.list();
		return list;
	}

	public void delete(Object obj) {
		print("删除实体");
		session.delete(obj);
	}

	@Before
	public void beginTrans() {
		print("开始事务");
		session.beginTransaction();
	}

	@After
	public void endTrans() {
		print("结束事务");
		session.getTransaction().commit();
	}

	/**
	 * 释放hibernate配置文件
	 */
	@AfterClass
	public static void releaseConfig() {
		System.out.println("release config");
		session.close();
		sessionFactory.close();
	}

	public void print(String info) {
		logger.debug(info);
	}

}
